#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
智能指令处理相关路由
"""

from flask import Blueprint, jsonify, request
from core import extensions

# 创建蓝图
command_bp = Blueprint('command', __name__)


@command_bp.route('/process_command', methods=['POST'])
def process_command():
    """
    处理单个指令
    
    请求体:
        {
            "command": "用户的自然语言指令",
            "dry_run": false,  # 可选，是否只解析不执行
            "confidence_threshold": 0.5  # 可选，置信度阈值
        }
    
    返回:
        {
            "code": 0,
            "message": "执行结果消息",
            "success": true/false,
            "data": {
                "command": "原始指令",
                "intent": "指令意图",
                "execution_result": {...},
                "processing_time": 处理时间
            }
        }
    """
    try:
        # 检查请求格式
        if not request.is_json:
            return jsonify({
                "code": 400,
                "message": "请求格式错误，需要JSON格式",
                "success": False,
                "data": None
            }), 400
        
        # 检查服务是否可用
        if not extensions.command_service:
            return jsonify({
                "code": 503,
                "message": "智能指令服务未初始化",
                "success": False,
                "data": None
            }), 503
        
        data = request.get_json()
        user_command = data.get('command', '').strip()
        
        if not user_command:
            return jsonify({
                "code": 400,
                "message": "缺少必要参数: command",
                "success": False,
                "data": None
            }), 400
        
        print(f"📝 处理指令: {user_command}")
        
        # 可选参数
        options = {
            'dry_run': data.get('dry_run', False),
            'confidence_threshold': data.get('confidence_threshold', 0.5),
            'save_history': data.get('save_history', True)
        }
        
        # 处理指令
        result = extensions.command_service.process_command(user_command, options)
        
        # 构建响应
        if result["success"]:
            execution_msg = result.get("execution_result", {}).get("message", "指令执行成功")
            return jsonify({
                "code": 0,
                "message": execution_msg,
                "success": True,
                "data": {
                    "command": user_command,
                    "intent": result.get("parsed_command", {}).get("intent", "unknown"),
                    "parsed_command": result.get("parsed_command", {}),
                    "execution_result": result.get("execution_result", {}),
                    "processing_time": result["processing_time"]
                }
            })
        else:
            error_msg = result.get("message", "指令执行失败")
            return jsonify({
                "code": 400,
                "message": error_msg,
                "success": False,
                "data": {
                    "command": user_command,
                    "error": result.get("message"),
                    "parsed_command": result.get("parsed_command"),
                    "processing_time": result.get("processing_time", 0)
                }
            }), 400
        
    except Exception as e:
        print(f"❌ 指令处理错误: {str(e)}")
        import traceback
        traceback.print_exc()
        return jsonify({
            "code": 500,
            "message": f"处理指令失败: {str(e)}",
            "success": False,
            "data": None
        }), 500


@command_bp.route('/quick_command', methods=['POST'])
def quick_command():
    """
    快捷指令执行接口（独立接口，不依赖WebSocket）
    专门用于前端快捷按钮直接调用
    
    智能处理策略:
    1. 如果是对话类意图（闲聊、讲笑话等）→ 调用大模型回复
    2. 如果是系统指令但执行失败 → 调用大模型生成友好的错误回复
    3. 如果是系统指令且执行成功 → 返回执行结果
    
    请求参数:
        - command: 自然语言指令 (必需)
    
    返回: 执行结果，包含详细的成功/失败信息
    """
    try:
        # 获取请求参数
        if not request.is_json:
            return jsonify({
                "code": 400,
                "message": "请求格式错误，需要JSON格式",
                "success": False,
                "data": None
            }), 400
        
        data = request.get_json()
        command = data.get('command', '').strip()
        
        if not command:
            return jsonify({
                "code": 400,
                "message": "缺少必要参数: command",
                "success": False,
                "data": None
            }), 400
        
        print(f"⚡ 收到快捷指令: {command}")
        
        # 检查服务是否可用
        if not extensions.command_service:
            return jsonify({
                "code": 503,
                "message": "智能指令服务未初始化",
                "success": False,
                "data": None
            }), 503
        
        if not extensions.intent_classifier:
            return jsonify({
                "code": 503,
                "message": "意图分类服务未初始化",
                "success": False,
                "data": None
            }), 503
        
        if not extensions.llm_client:
            return jsonify({
                "code": 503,
                "message": "LLM服务未初始化",
                "success": False,
                "data": None
            }), 503
        
        # 🆕 步骤1: 意图分类
        print(f"🔍 [意图分类] 分析指令意图...")
        intent_type = extensions.intent_classifier.classify(command)
        print(f"   意图类型: {intent_type}")
        
        # 🆕 步骤2: 根据意图类型选择处理策略
        if intent_type == 'conversation':
            # 对话类意图 - 直接调用大模型回复
            print(f"💬 [对话处理] 识别为对话类意图，调用大模型生成回复...")
            
            try:
                # 生成对话回复
                llm_response = extensions.llm_client.chat(
                    user_input=command,
                    system_prompt="你是一个友好的AI助手，请用简洁、自然的方式回答用户的问题。⚠️ 回答要简短精炼，控制在150字以内，适合快速阅读。",
                    max_tokens=250,
                    temperature=0.8
                )
                
                print(f"✅ [对话处理] 大模型回复生成成功")
                
                return jsonify({
                    "code": 0,
                    "message": llm_response,
                    "success": True,
                    "data": {
                        "command": command,
                        "intent": "conversation",
                        "response_type": "llm_conversation",
                        "llm_response": llm_response,
                        "processing_time": 0
                    }
                })
                
            except Exception as llm_error:
                print(f"❌ [对话处理] 大模型调用失败: {llm_error}")
                # 即使大模型失败，也返回友好的默认回复
                default_response = "抱歉，我现在无法回答您的问题。请稍后再试。"
                return jsonify({
                    "code": 200,  # 依然返回200，只是内容是默认回复
                    "message": default_response,
                    "success": True,
                    "data": {
                        "command": command,
                        "intent": "conversation",
                        "response_type": "default_fallback",
                        "llm_response": default_response,
                        "processing_time": 0
                    }
                })
        
        else:
            # 指令类意图 - 尝试执行系统指令
            print(f"🤖 [指令处理] 识别为系统指令，开始执行...")
            
            # 处理选项 - 快捷指令直接执行，不做干运行
            options = {
                "dry_run": False,
                "confidence_threshold": 0.3,  # 降低置信度阈值，让快捷指令更容易执行
                "save_history": True
            }
            
            # 处理指令
            result = extensions.command_service.process_command(command, options)
            
            # 🆕 步骤3: 根据执行结果决定返回策略
            if result["success"]:
                # 指令执行成功 - 返回执行结果
                execution_msg = result.get("execution_result", {}).get("message", "指令执行成功")
                print(f"✅ [指令处理] 指令执行成功: {execution_msg}")
                
                return jsonify({
                    "code": 0,
                    "message": execution_msg,
                    "success": True,
                    "data": {
                        "command": command,
                        "intent": result.get("parsed_command", {}).get("intent", "command"),
                        "response_type": "command_success",
                        "execution_result": result.get("execution_result", {}),
                        "processing_time": result["processing_time"]
                    }
                })
            else:
                # 指令执行失败 - 调用大模型生成友好的错误回复
                print(f"⚠️ [指令处理] 指令执行失败，调用大模型生成友好回复...")
                error_reason = result.get("message", "指令执行失败")
                
                try:
                    # 生成友好的错误回复
                    llm_response = extensions.llm_client.generate_friendly_error_response(
                        user_command=command,
                        error_reason=error_reason
                    )
                    
                    print(f"✅ [错误回复] 友好回复生成成功")
                    
                    return jsonify({
                        "code": 0,  # 返回200，但内容是友好的错误说明
                        "message": llm_response,
                        "success": True,  # 标记为成功，因为成功生成了回复
                        "data": {
                            "command": command,
                            "intent": result.get("parsed_command", {}).get("intent", "unknown"),
                            "response_type": "llm_error_fallback",
                            "llm_response": llm_response,
                            "original_error": error_reason,
                            "processing_time": result.get("processing_time", 0)
                        }
                    })
                    
                except Exception as llm_error:
                    print(f"❌ [错误回复] 大模型调用失败: {llm_error}")
                    # 大模型也失败了，返回默认友好回复
                    default_response = f"抱歉，我无法理解您的指令「{command}」。您可以试试说：播放音乐、创建文件、查询天气等。"
                    
                    return jsonify({
                        "code": 0,
                        "message": default_response,
                        "success": True,
                        "data": {
                            "command": command,
                            "intent": "unknown",
                            "response_type": "default_error_fallback",
                            "llm_response": default_response,
                            "original_error": error_reason,
                            "processing_time": result.get("processing_time", 0)
                        }
                    })
    
    except Exception as e:
        print(f"❌ 快捷指令执行错误: {str(e)}")
        import traceback
        traceback.print_exc()
        
        # 即使出现异常，也尝试返回友好的回复
        return jsonify({
            "code": 0,
            "message": "抱歉，处理您的请求时遇到了问题。请稍后再试。",
            "success": True,
            "data": {
                "command": data.get('command', ''),
                "intent": "unknown",
                "response_type": "exception_fallback",
                "llm_response": "抱歉，处理您的请求时遇到了问题。请稍后再试。",
                "error": str(e)
            }
        })


@command_bp.route('/batch_commands', methods=['POST'])
def batch_commands():
    """
    批量处理指令
    
    请求体:
        {
            "commands": ["指令1", "指令2", ...],
            "dry_run": false,  # 可选，是否只解析不执行
            "confidence_threshold": 0.5  # 可选，置信度阈值
        }
    
    返回:
        {
            "code": 0,
            "message": "批量处理完成",
            "success": true,
            "data": {
                "results": [...],
                "total": 总数,
                "success_count": 成功数,
                "failed_count": 失败数,
                "total_time": 总处理时间
            }
        }
    """
    try:
        # 检查请求格式
        if not request.is_json:
            return jsonify({
                "code": 400,
                "message": "请求格式错误，需要JSON格式",
                "success": False,
                "data": None
            }), 400
        
        # 检查服务是否可用
        if not extensions.command_service:
            return jsonify({
                "code": 503,
                "message": "智能指令服务未初始化",
                "success": False,
                "data": None
            }), 503
        
        data = request.get_json()
        commands = data.get('commands', [])
        
        if not isinstance(commands, list) or len(commands) == 0:
            return jsonify({
                "code": 400,
                "message": "commands 必须是非空数组",
                "success": False,
                "data": None
            }), 400
        
        print(f"📦 批量处理 {len(commands)} 个指令")
        
        # 可选参数
        options = {
            'dry_run': data.get('dry_run', False),
            'confidence_threshold': data.get('confidence_threshold', 0.5),
            'save_history': data.get('save_history', True)
        }
        
        # 批量处理指令
        import time
        start_time = time.time()
        results = extensions.command_service.batch_process_commands(commands, options)
        total_time = time.time() - start_time
        
        # 统计成功和失败数量
        success_count = sum(1 for r in results if r.get('success'))
        failed_count = len(results) - success_count
        
        print(f"✅ 批量处理完成: 成功 {success_count}/{len(results)}, 用时 {total_time:.2f}秒")
        
        return jsonify({
            "code": 0,
            "message": f"批量处理完成，成功 {success_count} 个，失败 {failed_count} 个",
            "success": True,
            "data": {
                "results": results,
                "total": len(results),
                "success_count": success_count,
                "failed_count": failed_count,
                "total_time": round(total_time, 2)
            }
        })
        
    except Exception as e:
        print(f"❌ 批量处理错误: {str(e)}")
        import traceback
        traceback.print_exc()
        return jsonify({
            "code": 500,
            "message": f"批量处理指令失败: {str(e)}",
            "success": False,
            "data": None
        }), 500


@command_bp.route('/command_history', methods=['GET'])
def get_command_history():
    """
    获取指令执行历史
    
    查询参数:
        - limit: 返回的最大记录数 (默认50)
    
    返回:
        {
            "code": 0,
            "message": "success",
            "success": true,
            "data": {
                "history": [...],
                "count": 记录数
            }
        }
    """
    try:
        # 检查服务是否可用
        if not extensions.command_service:
            return jsonify({
                "code": 503,
                "message": "智能指令服务未初始化",
                "success": False,
                "data": None
            }), 503
        
        limit = request.args.get('limit', 50, type=int)
        
        # 限制最大数量
        if limit > 100:
            limit = 100
        
        print(f"📜 获取历史记录，限制: {limit} 条")
        
        history = extensions.command_service.get_execution_history(limit)
        
        return jsonify({
            "code": 0,
            "message": f"成功获取 {len(history)} 条历史记录",
            "success": True,
            "data": {
                "history": history,
                "count": len(history),
                "limit": limit
            }
        })
        
    except Exception as e:
        print(f"❌ 获取历史记录错误: {str(e)}")
        import traceback
        traceback.print_exc()
        return jsonify({
            "code": 500,
            "message": f"获取历史记录失败: {str(e)}",
            "success": False,
            "data": None
        }), 500


@command_bp.route('/supported_commands', methods=['GET'])
def get_supported_commands():
    """
    获取支持的指令类型
    
    返回:
        {
            "code": 0,
            "message": "success",
            "success": true,
            "data": {
                "command_types": [...],
                "count": 类型数
            }
        }
    """
    try:
        print("📋 获取支持的指令类型列表")
        
        # 返回支持的指令类型列表
        command_types = [
            {
                "type": "music_search",
                "name": "音乐搜索",
                "description": "搜索和播放音乐",
                "examples": ["播放周杰伦的稻香", "播放一些轻音乐"],
                "icon": "🎵"
            },
            {
                "type": "online_search",
                "name": "网页搜索",
                "description": "在浏览器中搜索内容",
                "examples": ["搜索人工智能", "百度搜索天气预报"],
                "icon": "🔍"
            },
            {
                "type": "file_create",
                "name": "文件创建",
                "description": "创建新文件",
                "examples": ["创建一个文本文件叫test.txt", "新建一个文档"],
                "icon": "📝"
            },
            {
                "type": "file_delete",
                "name": "文件删除",
                "description": "删除文件",
                "examples": ["删除test.txt", "删除桌面上的文件"],
                "icon": "🗑️"
            },
            {
                "type": "file_open",
                "name": "文件打开",
                "description": "打开文件或文件夹",
                "examples": ["打开我的文档", "打开桌面"],
                "icon": "📂"
            },
            {
                "type": "app_open",
                "name": "应用打开",
                "description": "打开应用程序",
                "examples": ["打开微信", "启动浏览器"],
                "icon": "🚀"
            },
            {
                "type": "system_control",
                "name": "系统控制",
                "description": "控制系统功能",
                "examples": ["调高音量", "关闭屏幕"],
                "icon": "⚙️"
            },
            {
                "type": "weather_query",
                "name": "天气查询",
                "description": "查询天气信息",
                "examples": ["北京今天天气怎么样", "明天会下雨吗"],
                "icon": "🌤️"
            },
            {
                "type": "map_navigation",
                "name": "地图导航",
                "description": "查询地点和路线",
                "examples": ["导航到天安门", "附近的餐厅"],
                "icon": "🗺️"
            }
        ]
        
        return jsonify({
            "code": 0,
            "message": f"成功获取 {len(command_types)} 种支持的指令类型",
            "success": True,
            "data": {
                "command_types": command_types,
                "count": len(command_types)
            }
        })
        
    except Exception as e:
        print(f"❌ 获取指令类型错误: {str(e)}")
        import traceback
        traceback.print_exc()
        return jsonify({
            "code": 500,
            "message": f"获取支持的指令类型失败: {str(e)}",
            "success": False,
            "data": None
        }), 500

